const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const {auth} = require('../middleware/auth');


router.get('/all', async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT id, content, writer_id, created_at FROM quote ORDER BY created_at DESC'
    );
    res.json(rows);
  } catch (error) {
    console.error('获取所有作品列表失败:', error);
    res.status(500).json({
      message: '获取所有作品列表失败',
      error: error.message
    });
  }
});


router.get('/writer/:writerId', async (req, res) => {
  try {
    const writerId = req.params.writerId;
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;

    let query = `
      SELECT q.id, q.content, q.created_at, w.name as writer_name, w.id as writer_id 
      FROM quote q 
      LEFT JOIN writer w ON q.writer_id = w.id 
      WHERE q.writer_id = ?
      ORDER BY q.created_at DESC LIMIT ${pageSize} OFFSET ${offset}
    `;
    
    let countQuery = 'SELECT COUNT(*) as count FROM quote WHERE writer_id = ?';
    const countParams = [writerId];

    const [countRows] = await pool.execute(countQuery, countParams);
    const total = countRows[0].count;

    const [rows] = await pool.execute(query, [writerId]);

    res.json({
      total,
      quotes: rows
    });
  } catch (error) {
    console.error('获取名言列表失败:', error);
    res.status(500).json({
      message: '获取名言列表失败',
      error: error.message
    });
  }
});


router.get('/:id', async (req, res) => {
  try {
    const quoteId = req.params.id;
    
    const [rows] = await pool.execute(
      `SELECT q.id, q.content, q.writer_id, q.created_at, w.name as writer_name 
       FROM quote q 
       LEFT JOIN writer w ON q.writer_id = w.id 
       WHERE q.id = ?`,
      [quoteId]
    );

    if (rows.length === 0) {
      return res.status(404).json({ message: '名言不存在' });
    }

    res.json(rows[0]);
  } catch (error) {
    console.error('获取名言详情失败:', error);
    res.status(500).json({
      message: '获取名言详情失败',
      error: error.message
    });
  }
});

// 创建名言（需要认证）
router.post('/', auth, async (req, res) => {
  try {
    const { content, writer_id } = req.body;

    if (!content || !writer_id) {
      return res.status(400).json({ message: '名言内容和作家ID不能为空' });
    }

    // 检查作家是否存在
    const [writers] = await pool.execute(
      'SELECT id FROM writer WHERE id = ?',
      [writer_id]
    );

    if (writers.length === 0) {
      return res.status(400).json({ message: '作家不存在' });
    }

    const [result] = await pool.execute(
      'INSERT INTO quote (content, writer_id) VALUES (?, ?)',
      [content, writer_id]
    );

    const quoteId = result.insertId;
    
    // 返回创建的名言信息
    const [rows] = await pool.execute(
      `SELECT q.id, q.content, q.writer_id, q.created_at, w.name as writer_name 
       FROM quote q 
       LEFT JOIN writer w ON q.writer_id = w.id 
       WHERE q.id = ?`,
      [quoteId]
    );

    res.status(201).json(rows[0]);
  } catch (error) {
    console.error('创建名言失败:', error);
    res.status(500).json({
      message: '创建名言失败',
      error: error.message
    });
  }
});

// 更新名言（需要认证）
router.put('/:id', auth, async (req, res) => {
  try {
    const quoteId = req.params.id;
    const { content, writer_id } = req.body;

    if (!content) {
      return res.status(400).json({ message: '名言内容不能为空' });
    }

    // 检查名言是否存在
    const [existingQuotes] = await pool.execute(
      'SELECT id FROM quote WHERE id = ?',
      [quoteId]
    );

    if (existingQuotes.length === 0) {
      return res.status(404).json({ message: '名言不存在' });
    }

    // 如果提供了writer_id，检查作家是否存在
    if (writer_id) {
      const [writers] = await pool.execute(
        'SELECT id FROM writer WHERE id = ?',
        [writer_id]
      );

      if (writers.length === 0) {
        return res.status(400).json({ message: '作家不存在' });
      }
    }

    // 更新名言
    if (writer_id) {
      await pool.execute(
        'UPDATE quote SET content = ?, writer_id = ? WHERE id = ?',
        [content, writer_id, quoteId]
      );
    } else {
      await pool.execute(
        'UPDATE quote SET content = ? WHERE id = ?',
        [content, quoteId]
      );
    }

    // 返回更新后的名言信息
    const [rows] = await pool.execute(
      `SELECT q.id, q.content, q.writer_id, q.created_at, w.name as writer_name 
       FROM quote q 
       LEFT JOIN writer w ON q.writer_id = w.id 
       WHERE q.id = ?`,
      [quoteId]
    );

    res.json(rows[0]);
  } catch (error) {
    console.error('更新名言失败:', error);
    res.status(500).json({
      message: '更新名言失败',
      error: error.message
    });
  }
});

// 删除名言（需要认证）
router.delete('/:id', auth, async (req, res) => {
  try {
    const quoteId = req.params.id;

    // 检查名言是否存在
    const [existingQuotes] = await pool.execute(
      'SELECT id FROM quote WHERE id = ?',
      [quoteId]
    );

    if (existingQuotes.length === 0) {
      return res.status(404).json({ message: '名言不存在' });
    }

    await pool.execute('DELETE FROM quote WHERE id = ?', [quoteId]);

    res.json({ message: '名言删除成功' });
  } catch (error) {
    console.error('删除名言失败:', error);
    res.status(500).json({
      message: '删除名言失败',
      error: error.message
    });
  }
});

module.exports = router; 